import {
    Card,
    Breadcrumb,
    Form,
    Button,
    Radio,
    Input,
    Upload,
    Space,
    Select,
    message
} from 'antd'
import { PlusOutlined } from '@ant-design/icons'
import { Link, useSearchParams } from 'react-router-dom'
import './index.scss'
import ReactQuill from 'react-quill'
import 'react-quill/dist/quill.snow.css'
import {  createArticleAPI, getArticleById,updateArticleById } from '@/apis/article'
import { useEffect, useState } from 'react'
import { useChannel } from '@/hooks/useChannel'

const { Option } = Select

const Publish = () => {

    //获取频道列表
    const {channelList} = useChannel()

    //提交表单
    const handlerFinish = (values) => {
        console.log(values)
        //校验封面类型imagetype是否和实际图片列表数量相等的
        if(imageList.length!=imageType){
            message.error("封面类型和图片数量不匹配 ")
            return ;
        }
        const { title, content, cover, channel_id } = values;
        //1.处理收集到的表单数据
        const reqData = {
            title,
            content,
            cover: {
                type: imageType,
                //这里url处理逻辑在新增时的逻辑
                //编辑时需要处理
                images: imageList.map(item=>{
                    if(item.response){
                        return  item.response.data.url
                    }else{
                        return item.url
                    }
                })
            },
            channel_id
        }
        //2.接口提交
        //处理调用不同接口  新增状态  新增接口  编辑状态，编辑接口
        if(articleId){
            updateArticleById({...reqData,id:articleId})
        }else{
            createArticleAPI(reqData)
        }
        message.success("发布成功!")
    }

    //上传回调
    const [imageList,setImageList] = useState([])
    const handlerUploadChange = (value)=>{
        console.log(value.fileList)
       setImageList(value.fileList)
    }

    //切换图片封面类型
    const [imageType,setImageType] = useState(0)
    const handlerTitleChange = (e)=>{
        setImageType(e.target.value)
    }

    //回填数据
    const [searchParams] = useSearchParams()
    const articleId = searchParams.get("id")
    //获取实例 
    const [form] = Form.useForm()
    useEffect(()=>{
        //1.先通过id获取数据
      async function getArticle(){
          const res =  await getArticleById(articleId)
          const data = res.data
          form.setFieldsValue({
            ...data,
            type:data.cover.type
          })
          //回填图片列表
          setImageType(data.cover.type)
          //显示图片
          setImageList(data.cover.images.map(url=>{
            return {url}
          }))
        }
        //2.调用实例方法完成回调
        if(articleId){
            getArticle()
        }
    },[articleId,form])

    return (
        <div className="publish">
            <Card
                title={
                    <Breadcrumb items={[
                        { title: <Link to={'/'}>首页</Link> },
                        { title: `${articleId?'编辑':'新增'}文章`},
                    ]}
                    />
                }
            >
                <Form
                    labelCol={{ span: 4 }}
                    wrapperCol={{ span: 16 }}
                    initialValues={{ type: imageType }}
                    onFinish={handlerFinish}
                    form={form}
                >
                    <Form.Item
                        label="标题"
                        name="title"
                        rules={[{ required: true, message: '请输入文章标题' }]}
                    >
                        <Input placeholder="请输入文章标题" style={{ width: 400 }} />
                    </Form.Item>
                    <Form.Item
                        label="频道"
                        name="channel_id"
                        rules={[{ required: true, message: '请选择文章频道' }]}
                    >
                        <Select placeholder="请选择文章频道" style={{ width: 400 }}>
                            {channelList.map(item => <Option key={item.id} value={item.id}>{item.name}</Option>)}
                        </Select>
                    </Form.Item>

                    <Form.Item label="封面">
                        <Form.Item name="type">
                            <Radio.Group onChange={handlerTitleChange}>
                                <Radio value={1}>单图</Radio>
                                <Radio value={3}>三图</Radio>
                                <Radio value={0}>无图</Radio>
                            </Radio.Group>
                        </Form.Item>
                        {imageType>0 &&
                         <Upload
                         listType="picture-card"
                         showUploadList
                         name='image'
                         action={'http://geek.itheima.net/v1_0/upload'}
                         onChange={handlerUploadChange}
                         maxCount={imageType}
                         fileList={imageList}
                     >
                         <div style={{ marginTop: 8 }}>
                             <PlusOutlined />
                         </div>
                     </Upload>}
                       
                    </Form.Item>

                    <Form.Item
                        label="内容"
                        name="content"
                        rules={[{ required: true, message: '请输入文章内容' }]}
                    >
                        <ReactQuill
                            className="publish-quill"
                            theme="snow"
                            placeholder="请输入文章内容"
                        >
                        </ReactQuill>
                    </Form.Item>

                    <Form.Item wrapperCol={{ offset: 4 }}>
                        <Space>
                            <Button size="large" type="primary" htmlType="submit">
                                发布文章
                            </Button>
                        </Space>
                    </Form.Item>
                </Form>
            </Card>
        </div>
    )
}

export default Publish